// src/services/activity.ts
export type Activity = {
  id: number
  title: string
  cover: string
  startAt: number
  endAt: number
  heat: number
  desc: string
  address: string
  quota: number
  signedCount: number
}

const now = Date.now()
const H = 3600 * 1000
const D = 24 * H

import { activitySignupPost } from '@/api/allApi'


// —— 工具：读取“已报名人数”（来自本地模拟）
function withLocalSignedCounts(list: Activity[], userId?: string) {
  const data = list.map(a => ({ ...a }))
  // 聚合所有用户本地报名记录，叠加展示人数（仅用于演示）
  try {
    const all = uni.getStorageInfoSync().keys
      .filter(k => k.startsWith('signup_'))
      .map(k => uni.getStorageSync(k))
      .filter(Boolean) as Array<{ activityId: number }>
    const incMap = new Map<number, number>()
    all.forEach(({ activityId }) => incMap.set(activityId, (incMap.get(activityId) || 0) + 1))
    data.forEach(a => { a.signedCount += incMap.get(a.id) || 0 })
  } catch {}
  return data
}

// —— 列表
export async function listActivities(
  sort: '2' | '3',
  page = 1,
  pageSize = 8
): Promise<{ list: Activity[]; more: boolean }> {
  const token = localStorage.getItem('token')
  const response = await fetch(`http://www.crazyzzcc.online:32004/campus/activity?status=已发布&sort=${sort}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

  const data_a = await response.json()

  let data = data_a.data.items

  data.forEach(item => {
    item.cover = 'https://images.unsplash.com/photo-1529101091764-c3526daf38fe?q=80&w=1200';
  });

  const start = (page - 1) * pageSize
  const end = start + pageSize
  return { list: data.slice(start, end), more: end < data.length }
}

// —— 详情
export async function getActivityById(id: string): Promise<Activity | null> {
  const token = localStorage.getItem('token')
  const response = await fetch(`http://www.crazyzzcc.online:32004/campus/activity/one/${id}`, {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
  })
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`)
  }
  const data_a = await response.json()
  let data = data_a.data

  return data || null
}

// —— 报名（本地模拟：登录后按 userId+activityId 记一条）
export async function signupActivity(activityId: number): Promise<boolean> {
  const userInfoStr = localStorage.getItem('userInfo')
  const userInfo = JSON.parse(userInfoStr);
  console.log(userInfo['id'])
  const token = localStorage.getItem('token')
  const response = await fetch(`http://www.crazyzzcc.online:32004/campus/activity/signup?campus_activity_id=${activityId}&crmid=${userInfo['data']['id']}`, {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
  })
  const responseData = await response.json();
  if (responseData['data']['items'].length >= 1) {
    return false
  } else {
    const response = activitySignupPost(activityId)
    if (response['code'] == 200) {
      return true
    }
  }
  return true
}

function sleep(ms: number) { return new Promise(r => setTimeout(r, ms)) }
